import login from '../../apis/login';
import router from '../../router';

export default {
  namespaced: true,
  state: {
    form: {
      username: '',
      password: '',
      token: '',
    },
  },
  mutations: {
    getUsername(state, data) {
      state.form.username = data;
    },
    getPassword(state, data) {
      state.form.password = data;
    },
  },
  actions: {
    async login({ state }) {
      if (localStorage.token) {
        router.push({ name: 'home' });
        return;
      }
      const result = await login.login({
        username: state.form.username,
        password: state.form.password,
      }).catch(() => {});
      if (result) {
        localStorage.token = result.data;
        state.token = result.data;
        router.push({ name: 'home' });
      }
    },
  },
};
